<template>
  <l-layout class="l-tab-page">
    <l-panel style="padding:0;">
      <template #toolRight>
        <el-button-group>
          <el-button
            size="mini"
            icon="el-icon-refresh-left"
            @click="handleRefresh"
          ></el-button>
        </el-button-group>
      </template>
      <div class="l-rblock">
        <l-table
          :loading="tableLoading"
          :columns="columns"
          :dataSource="tableData"
          row-key="f_Id"
          :isPage="true"
          :pageTotal="tableTotal"
          :tablePage.sync="tableCurrentPage"
          @loadPageData="turnTablePage"
        >
          <template v-slot:f_CreateDate="scope">
            {{ lr_dateFormat(scope.row.f_CreateDate) }}
          </template>
          <template v-slot:f_Type="scope">
            <el-tag v-if="scope.row.f_Type != 1" size="mini" type="info"
              >{{ $t('草稿') }}</el-tag
            >
            <el-tag v-else size="mini" type="success">{{ $t('正式') }}</el-tag>
          </template>
          <template v-slot:f_IsVerison="scope">
            <el-switch
              v-model="scope.row.f_IsVerison"
              :disabled="true"
              @change="handleEnableChange(scope.row)"
            >
            </el-switch>
          </template>
          <l-table-btns
            :btns="tableBtns"
            @click="lr_handleTableBtnClick"
          ></l-table-btns>
        </l-table>
      </div>
    </l-panel>

    <l-fullscreen-dialog
      :title="`${$t('模板预览')}-${previewTitle}`"
      :visible.sync="previewVisible"
      :hasBtns="false"
      :showOk="false"
      @opened="handlePreviewOpened"
      @closed="handlePreviewClosed"
    >
      <preview-form
        v-if="ready"
        :pageSchema="printSchema"
        :isShowClose="false"
      ></preview-form>
    </l-fullscreen-dialog>

    <l-fullscreen-dialog
      title="打印模板"
      :visible.sync="formVisible"
      ref="formDialog"
      @opened="handleOpenedForm"
      @close="handleCloseForm"
      @ok="
        (showLoading, hideLoading) => handleSave(showLoading, hideLoading, 1)
      "
    >
      <template #headerRight>
        <el-button size="mini" type="warning" @click="handleSaveDraft">{{
          $t("暂存")
        }}</el-button>
      </template>
      <print-form ref="form"></print-form>
    </l-fullscreen-dialog>
  </l-layout>
</template>

<script>
const api = window.$api.print.printTemplate;
import components from "./config/component";
import previewForm from "./preview";
import PrintForm from "./form";
export default {
  components: {
    previewForm,
    PrintForm
  },
  props: {
    schemeInfoId: String,
    schemeId: String,
    updateSchemeId: Function,
    historyVisible: Boolean,
  },
  data() {
    return {
      noAuth: true,
      columns: [
        { label: "创建人", prop: "f_CreateUserName", minWidth: "160" },
        { label: "创建时间", prop: "f_CreateDate", minWidth: "160" },
        { label: "状态", prop: "f_Type", width: "64", align: "center" },
        {
          label: "当前版本",
          prop: "f_IsVerison",
          width: "80",
          align: "center",
        },
      ],
      tableBtns: [
        { prop: "Preview", label: this.$t("预览"),width:100 },
        { prop: "Edit", label: this.$t("编辑"),width:100 },
      ],
      tableLoading: false,
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableData: [],

      // 表单预览
      previewVisible: false,
      previewTitle: "",
      previewLoading: false,
      formEditRow: null,

      components: components,

      printSchema: {
        pageConfig: {},
        pages: [
          {
            components: [],
          },
        ],
      },
      ready: false,

      // 表单编辑
      formVisible: false,
    };
  },
  computed: {},
  methods: {
    handleRefresh() {
      this.loadTablePageData();
    },
    loadTablePageData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate DESC",
      };
      api
        .getHistoryPage(this.schemeInfoId, queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = data.rows.map((t) => {
            return { ...t, f_IsVerison: t.f_Id == this.schemeId };
          });
          this.tableTotal = data.records;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePageData(true);
    },
    handleEnableChange(row) {
      const data = {
        templateid: row.f_Id,
        state: row.f_IsVerison,
      };
      this.updateSchemeId(row.f_Id);
      this.tableData.forEach((item) => {
        if (item.f_Id != row.f_Id) {
          item.f_IsVerison = false;
        }
      });
      api.updateHistory(data, row.f_Id).then(() => {
        this.$message({
          type: "success",
          message: this.$t("更新成功!"),
        });
      });
    },

    handlePreview($index, row) {
      this.formEditRow = row;
      this.previewTitle = this.lr_dateFormat(row.f_CreateDate);
      this.previewVisible = true;
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm("编辑");
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    getSchema(data) {
      if (data.lrPrintTemplateEntity) {
        const schema = JSON.parse(data.lrPrintTemplateEntity.f_Component);
        schema.pages.forEach((page) => {
          const components = [];
          page.components.forEach((config) => {
            const component = this.components.find(
              (t) => t.type == config.componentType
            );
            const _component = {
              label: component.label,
              type: component.type,
              icon: component.icon,
              config: config,
            };

            components.push(_component);
          });
          page.components = components;
        });

        const printSchema = {};
        printSchema.pageConfig = schema.pageConfig;
        printSchema.pages = schema.pages;
        return printSchema;
      }

      this.$message({
        type: "error",
        message: this.$t("数据加载错误!"),
      });
      this.previewVisible = false;
    },
    async handlePreviewOpened(showLoading, hideLoading) {
      showLoading("加载数据中...");
      const data = await this.$awaitWraper(
        api.getHistory(this.formEditRow.f_Id)
      );
      this.printSchema = this.getSchema(data);
      this.ready = true;

      hideLoading();
    },
    handlePreviewClosed() {
      this.ready = false;
      this.printSchema = {
        pageConfig: {},
        pages: [
          {
            components: [],
          },
        ],
      };
    },

    handleSaveDraft() {
      this.handleSave(
        this.$refs.formDialog.showLoading,
        this.$refs.formDialog.hideLoading,
        2
      );
    },
    async handleSave(showLoading, hideLoading, type) {
      showLoading("保存数据中...");
      if (await this.$refs.form.validateForm()) {
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEdit ? this.formEditRow.f_TemplateInfoId : "",
          isEdit: this.formEdit,
          type: type,
        });
        if (res) {
          const msg = this.formEdit ? this.$t("更新成功!") : this.$t("新增成功!");
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTablePageData();
          this.formVisible = false;
          this.$emit("loadTablePageIndexData");
          this.$emit("update:historyVisible", false)
        }
      }
      hideLoading();
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        const data = await this.$awaitWraper(
        api.getHistory(this.formEditRow.f_Id)
      );
      this.$refs.form.setForm(data)
        hideLoading();
      }
    },
  },
};
</script>
